//
//  CalendarControl.m
//  CToolBox
//
//  Created by crj on 16/8/31.
//  Copyright © 2016年 oyf. All rights reserved.
//

#import "CalendarControl.h"
#import "CalendarModel.h"
#import "NSDate+Compare.h"

#define kContentWidth 285.0
#define kSectionHeight 40

@interface CalendarControl()
{
    NSInteger _sections;//日期总共有几行
    NSArray *_weekNames;//星期显示名
    NSMutableArray *_datesOfPageArray;//一张日历中需要显示的日期
    
    int _year;
    int _month;
    int _day;
}

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *headerContentView;
@property (nonatomic, strong) UIView *weekContentView;
@property (nonatomic, strong) UIView *dayContentView;


//headerContentView
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) UILabel *leftLine;
@property (nonatomic, strong) UILabel *rightLine;
@property (nonatomic, strong) UILabel *dateLabel;

//weekContentView
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation CalendarControl

+ (CalendarControl *)showWithList:(NSMutableArray *)list{
    CalendarControl *control = [[CalendarControl alloc] init];
    control.dataSource = list;
    [control setConfig];
    [control setUI];
    
    control.frame = [UIApplication sharedApplication].keyWindow.bounds;
    control.alpha = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:control];
    
    [UIView animateWithDuration:0.5 animations:^{
        control.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    return control;
}

- (void)close{
    
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
       
        [self addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}


- (void)setConfig{
    
    _datesOfPageArray = [[NSMutableArray alloc] init];
    _sections = 5;
    _weekNames = @[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",];
    
    [self getNowDate];
    [self datesThisPage];
}

- (void)setUI{
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor redColor];
    [self addSubview:_contentView];
    
    _headerContentView = [[UIView alloc] init];
    _headerContentView.backgroundColor = HEXCOLOR(@"4f5f6f", 1);
    [_contentView addSubview:_headerContentView];
    
    _weekContentView = [[UIView alloc] init];
    _weekContentView.backgroundColor = HEXCOLOR(kColorBlue4, 1);
    [_contentView addSubview:_weekContentView];
    
    _dayContentView = [[UIView alloc] init];
    _dayContentView.backgroundColor = [UIColor greenColor];
    [_contentView addSubview:_dayContentView];
    
    
    [self initHeaderContentView];
    [self initWeekContentView];
    [self initDaysContentView];
    
    
}


- (void)initHeaderContentView{

    /*
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.backgroundColor = [UIColor clearColor];
    _leftBtn.titleLabel.font = [UIFont fontWithName:kFontIcon size:22];
    [_leftBtn setTitle:[NSString iconCode:@"zuojiantou"] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:@selector(lastAction) forControlEvents:UIControlEventTouchUpInside];
    [_headerContentView addSubview:_leftBtn];
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.backgroundColor = [UIColor clearColor];
    _rightBtn.titleLabel.font = [UIFont fontWithName:kFontIcon size:22];
    [_rightBtn setTitle:[NSString iconCode:@"youjiantou"] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[UIColor colorWithWhite:1 alpha:0.5] forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [_headerContentView addSubview:_rightBtn];
    
    _leftLine = [[UILabel alloc] init];
    _leftLine.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.1];
    [_headerContentView addSubview:_leftLine];
    
    _rightLine = [[UILabel alloc] init];
    _rightLine.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.1];
    [_headerContentView addSubview:_rightLine];
    */
    _dateLabel = [[UILabel alloc] init];
    _dateLabel.font = [UIFont systemFontOfSize:13];
    _dateLabel.textColor= [UIColor whiteColor];
    _dateLabel.textAlignment = NSTextAlignmentCenter;
    [_headerContentView addSubview:_dateLabel];
    
    _dateLabel.text = [NSDate stringFromeDate:[NSDate date] dateFormat:@"yyyy-MM月"];

    
    
}

- (void)initWeekContentView{
    
    for(int i=0; i<_weekNames.count; i++){
        CGFloat itemWidth = kContentWidth/_weekNames.count;
        
        NSString *name = _weekNames[i];
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(itemWidth*i, 0, itemWidth, kSectionHeight);
        label.font = [UIFont systemFontOfSize:10];
        label.text = name;
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        [_weekContentView addSubview:label];
    }
}

- (void)initDaysContentView{
    
    for(UIView *view in _dayContentView.subviews){
        [view removeFromSuperview];
    }
    
    _sections = _datesOfPageArray.count/7;
    
    int section = 0;
    int row = 0;
    
    CGFloat itemWidth = kContentWidth/7;

    //填充每周的背景色
    
    NSArray *colors = @[[UIColor whiteColor],HEXCOLOR(@"e1ecf7", 1)];
    for(int i=0; i<_sections; i++){
        
        UIView *sectionView = [[UIView alloc] init];
        sectionView.frame = CGRectMake(0, i*kSectionHeight, kContentWidth, kSectionHeight);
        sectionView.backgroundColor = colors[i%2];
        [_dayContentView addSubview:sectionView];
    }
    
    //填充所有日期
    for(int i=0; i<_datesOfPageArray.count; i++){
        
       
        //已经签过到的日期
        CalendarModel *model = _datesOfPageArray[i];
        for(NSNumber *d in _dataSource){
            if([NSDate isSameDayWithOldDate:[NSDate dateWithDay:[d intValue]] newDate:model.date]){
                model.isSelect = YES;
                break;
            }
        }

        
        
        int day = [self getDayNumberWithDate:model.date];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(itemWidth*row+5, kSectionHeight*section+5, itemWidth-10, kSectionHeight-10);
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        [button setTitle:[NSString stringWithFormat:@"%d",day] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"日历打开底图"] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        if(model.isCurrentPage){
            [button setTitleColor:HEXCOLOR(@"4f5f6f", 1) forState:UIControlStateNormal];
        }else{
            [button setTitleColor:HEXCOLOR(@"a1b1c2", 1) forState:UIControlStateNormal];
        }
        [_dayContentView addSubview:button];
        
        
        if(model.isSelect){
            button.selected = YES;
        }
        row++;
        if(row == 7){
            row = 0;
            section++;
        }
        
    }
    
}




- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    
    //父视图
    _contentView.frame = CGRectMake(0, 0, kContentWidth, 0);
    _headerContentView.frame = CGRectMake(0, 0, _contentView.frame.size.width, kSectionHeight);
    _weekContentView.frame = CGRectMake(0, _headerContentView.yj_bottom, _contentView.frame.size.width, kSectionHeight);
    _dayContentView.frame = CGRectMake(0, _weekContentView.yj_bottom, _contentView.frame.size.width, _sections*kSectionHeight);
    
    _contentView.yj_height = _dayContentView.yj_bottom;
    _contentView.center = [UIApplication sharedApplication].keyWindow.center;
    
    
    //headerContentView
    _leftBtn.frame = CGRectMake(0, 0, kSectionHeight, kSectionHeight);
    _leftLine.frame = CGRectMake(_leftBtn.frame.size.width, 0, 0.5, kSectionHeight);
    
    _rightBtn.frame = CGRectMake(kContentWidth-kSectionHeight, 0, kSectionHeight, kSectionHeight);
    _rightLine.frame = CGRectMake(_rightBtn.frame.origin.x-0.5, 0, 0.5, kSectionHeight);
    _dateLabel.frame = CGRectMake(0, 0, 200, kSectionHeight);
    _dateLabel.center = CGPointMake(_headerContentView.frame.size.width/2, _headerContentView.frame.size.height/2);
    //weekContentView
    
}


#pragma mark - Event Respond
//上一月
- (void)lastAction{

    
    if(_month-1 == 0){
        _month = 12;
        _year = _year-1;
    }else{
        _month--;
    }

    
    [self datesThisPage];
    [self initDaysContentView];
}

//下一月
- (void)nextAction{

    if(_month+1 == 13){
        _month = 1;
        _year = _year+1;
    }else{
        _month++;
    }
    [self datesThisPage];
    [self initDaysContentView];
    
}


#pragma mark - 计算每页日历 需要显示的日期

- (void)datesThisPage{
    
    NSString *thisPageTitle = [NSString stringWithFormat:@"%d-%d月",_year,_month];
    _dateLabel.text = thisPageTitle;
    
    //某月的天数(当前页)
    int daysOfAMonth = [self getCountOfMonthByYear:_year andMonth:_month];
    //某月的第一天是周几
    int weekOfFirstDay = [self getWeekNameByFirstDayOfMonthWithYear:_year andMonth:_month];
    
    
    NSMutableArray *allDays = [[NSMutableArray alloc] init];
    NSMutableArray *currentDays = [[NSMutableArray alloc] init];
    NSMutableArray *lastMonthDays = [[NSMutableArray alloc] init];
    //当月
    for(int i=1; i<=daysOfAMonth; i++){
        
        NSDate *d = [self dateWithYear:_year month:_month day:i];

        CalendarModel *model = [[CalendarModel alloc] init];
        model.date = d;
        model.isCurrentPage = YES;
        [currentDays addObject:model];
        
    }
    
    
    //上月
    
    if(weekOfFirstDay != 1){
        //上月的最后一天
        NSArray *array = [self daysWithLastMonthWithWeek:weekOfFirstDay];
        [lastMonthDays addObjectsFromArray:array];
    }
    
    [allDays addObjectsFromArray:lastMonthDays];
    [allDays addObjectsFromArray:currentDays];
    //下月
    [self daysWithNextMonth:allDays];

    
    [_datesOfPageArray removeAllObjects];
    [_datesOfPageArray addObjectsFromArray:allDays];
}

//获取某月的上月天数(获取上个月需要展示的日期)
- (NSMutableArray *)daysWithLastMonthWithWeek:(int)week{
    
    int m = _month-1;
    int y = _year;
    
    if(m==0){
        m = 12;
        y = _year-1;
    }
    
    
    NSMutableArray *lastArray = [[NSMutableArray alloc] init];
    //上个月天数
    int daysOfAMonth = [self getCountOfMonthByYear:y andMonth:m];
    
    
    int index = week-1;
    for(int i=index; i>0; i--){
        NSDate *d = [self dateWithYear:y month:m day:daysOfAMonth];
        [lastArray addObject:d];
        daysOfAMonth--;
       
    }
    
    //摆正顺序
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for(NSInteger i=lastArray.count-1; i>=0; i--){
//        [tempArray addObject:lastArray[i]];
        NSDate *d = lastArray[i];
        CalendarModel *model = [[CalendarModel alloc] init];
        model.date = d;
        model.isCurrentPage = NO;
        [tempArray addObject:model];
    }
    
    return tempArray;

}

//获取下个月需要展示的日期

- (void)daysWithNextMonth:(NSMutableArray *)allDays{
    //下个月需要几天
    int need = 7 - allDays.count%7;
    if(need == 7){
        need = 0;
    }
    
    int m = _month+1;
    int y = _year;
    
    if(m==13){
        m = 1;
        y = _year+1;
    }
    
    for(int i=0; i<need; i++){
        NSDate *d = [self dateWithYear:y month:m day:i+1];
        CalendarModel *model = [[CalendarModel alloc] init];
        model.date = d;
        model.isCurrentPage = NO;
        [allDays addObject:model];
    }
    
}

//某天的星期 在一周中排第几
- (int)indexInSectionWithWeek:(int)week{
    
    return week-1;
    
}

#pragma mark - 获取当前日期
- (void)getNowDate
{
    //获取当前时间
    NSDate *nowDate=[NSDate date];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *nowDateStr=[dateformatter stringFromDate:nowDate];
    NSArray *currentArr = [nowDateStr componentsSeparatedByString:@"-"];
    _year = [[currentArr objectAtIndex:0]intValue];
    _month = [[currentArr objectAtIndex:1]intValue];
    _day = [[currentArr objectAtIndex:2]intValue];
    
}



#pragma mark - 计算每个月的第一天是周几

- (int)getWeekNameByFirstDayOfMonthWithYear:(int)year andMonth:(int)month
{

    NSDate *date = [self dateWithYear:year month:month day:1];
    return [self getWeekdayFromDate:date];
}

#pragma mark - 获取指定日是几号

- (int)getDayNumberWithDate:(NSDate *)date{
    
    //获取当前时间
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *nowDateStr=[dateformatter stringFromDate:date];
    NSArray *currentArr = [nowDateStr componentsSeparatedByString:@"-"];
   
    return [[currentArr objectAtIndex:2]intValue];
}

#pragma mark - 获取指定日是周几

- (int)getWeekdayFromDate:(NSDate*)date
{
    NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    calendar.timeZone = [NSTimeZone systemTimeZone];
    NSDateComponents* components = [[NSDateComponents alloc] init] ;
    NSInteger unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |
    NSCalendarUnitDay |
    NSCalendarUnitWeekday |
    NSCalendarUnitHour |
    NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    components = [calendar components:unitFlags fromDate:date];
    NSInteger weekday = [components weekday];
    return (int)weekday;
}

#pragma mark - 计算某个月有几天

- (int)getCountOfMonthByYear:(int)year andMonth:(int)month
{
    if(month==2)
    {
        if((year%4==0&&year%100!=0)||year%400==0)return 29;
        else return 28;
    }
    switch(month)
    {
        case 1:return 31;
        case 3:return 31;
        case 4:return 30;
        case 5:return 31;
        case 6:return 30;
        case 7:return 31;
        case 8:return 31;
        case 9:return 30;
        case 10:return 31;
        case 11:return 30;
        case 12:return 31;
    }
    return 0;
}

//生成一个date对象
- (NSDate *)dateWithYear:(int)year month:(int)month day:(int)day{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyy-MM-dd"];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d",year,month,day]];
    return date;
}


@end
